#include "comm.h"

comm_t comm = {
	.step = 0,
	.cnt  = 0,
};

/**
 * @brief  数据发送
 * @param  
 * @retval 无
 */
void comm_tx(uint8_t fun, uint8_t *data, uint8_t datalen)
{
		uint8_t SendBuff[60];
    uint8_t len = 0;

    /* 帧头 */
    SendBuff[len++] = 0xFD;
    SendBuff[len++] = 0xDF;

    /* 总长度 先占位 */
    SendBuff[len++] = 0;

    /* 功能帧 */
    SendBuff[len++] = fun;

    /* 数据 */
    for (uint16_t max = (datalen + len), now = len; len < max; len++) {
        SendBuff[len] = data[len - now];
    }

    /* 获取实际长度 */
    SendBuff[2] = len;

    /* 校验位 */
    SendBuff[len] = 0;
    for (uint16_t i = 0; i < len; i++) {
        SendBuff[len] += SendBuff[i];
    }
		
		HAL_UART_Transmit(&huart_comm, SendBuff, len+1, 0xff);
}

/**
 * @brief  蓝牙发送8位数据
 * @param  
 * @retval 无
 */
void comm_tx_u8(uint8_t fun, uint8_t data)
{
	comm_tx(fun, &data, 1);
}

/**
 * @brief  蓝牙发送16位数据
 * @param  
 * @retval 无
 */
void comm_tx_u16(uint8_t fun, uint16_t data)
{
	uint8_t u8_data[2] = {
		data>>8,
		data & 0xff,
	};
	
	
	comm_tx(fun, u8_data, 2);
}

/**
 * @brief  根据上位机命令做出对应响应
 * @param  void
 * @retval void
 */
void comm_switch(void)
{
	uint8_t *rxdata = &comm.buff[4];
	
	switch(comm.buff[3])
	{
		case motor_angle:

			break;
	}
}
		
/**
* @brief  上位机指令解析 
 * @param  void
 * @retval void
 */
void comm_parsing(void)
{
	uint8_t ack = 0;
	
	for (int i=0; i < comm.rxlen; i++) {
		ack += comm.buff[i];
	}
	
	if (ack == comm.buff[comm.rxlen]) {
		comm_switch();
	}	
}

/**
 * @brief  蓝牙接收服务函数
 * @param  
 * @retval 无
 */
void comm_uart_handler(uint8_t data)
{
	switch(comm.step) {
		case 0:
			comm.cnt = 0;
			comm.buff[comm.cnt++] = data;
			if (data == 0xFD) {
				comm.step = 1;
			}
			break;
		case 1:
			comm.buff[comm.cnt++] = data;
			if (data == 0xDF) {
				comm.step = 2;
			} else {
				comm.step = 0;
			}
			break;
		case 2:
			comm.buff[comm.cnt++] = data;
		
			if (comm.cnt - 1 == 2) {
				comm.rxlen = data;
			}
			
			if (comm.cnt > comm.rxlen) {
				comm.step = 3;
				comm.cnt = 0;
			}
			
			break;
			
		default :
		{};
	}
	
	if (comm.step == 3) {
		comm.step = 0;
		comm_parsing();
	}
}
/******************* (C) COPYRIGHT 2025 FUYEBING*****END OF FILE************/
